package com.tender.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RateLimitController2 {

    @GetMapping("/rateLimit/byUrl")
    public String byUrl() {
        return "按rest地址，限流测试ok";
    }

    @GetMapping("/rateLimit/byResource")
    @SentinelResource(value = "byResource", blockHandler = "byResourceHandler")
    public String byResource() {
        return "按照资源名称 SentinelResource 限流测试：O(∩_∩)O";
    }

    /**
     * 如果有入参，照抄，最后面加上 {@link BlockException}
     * @param blockException
     * @return
     */
    public String byResourceHandler(BlockException blockException) {
        return "服务不可用，触发了@SentinelResource启动：/(ㄒoㄒ)/~~";
    }


    @GetMapping("/rateLimit/byFallback/{i}")
    @SentinelResource(value = "byFallback", blockHandler = "byBlockHandler", fallback = "byFallback")
    public String rateLimitByFallback(@PathVariable("i") Integer i) {
        if (i == 0) {
            throw new RuntimeException("i == 0 异常");
        }
        return "使用注解并使用, Fallback, 服务可用：O(∩_∩)O";
    }

    public String byBlockHandler(@PathVariable("i") Integer i, BlockException blockException) {
        System.out.println("配置了自定义限流, " + blockException.getMessage());
        return "服务不可用：(；′⌒`), 这是自定义返回的字符串";
    }

    public String byFallback(@PathVariable("i") Integer i, Throwable throwable) {
        System.out.println("程序逻辑异常, " + throwable.getMessage());
        return "逻辑异常：/(ㄒoㄒ)/~~, 这是自定义返回的字符串";
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "testHotKeyBlockHandler")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                             @RequestParam(value = "p2", required = false) String p2) {
        return "testHotKey 正常访问 O(∩_∩)O ...";
    }

    public String testHotKeyBlockHandler(@RequestParam(value = "p1", required = false) String p1,
                                         @RequestParam(value = "p2", required = false) String p2, BlockException blockException) {
        return "testHotKey 被限流了 /(ㄒoㄒ)/~~ ...";
    }

}
